package com.srwl.mytx.im.handler;

import android.text.TextUtils;
import android.util.Log;

import com.srwl.mytx.Constant;
import com.srwl.mytx.im.MessageBuilder;
import com.srwl.mytx.im.core.MessageReceivedQueue;
import com.srwl.mytx.im.core.NettyTcpClient;
import com.srwl.mytx.im.protobuf.MessageProtobuf;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * <p>@ProjectName:     NettyChat</p>
 * <p>@ClassName:       TCPReadHandler.java</p>
 * <b>
 * <p>@Description:     消息接收处理handler</p>
 * </b>
 */
public class TCPReadHandler extends ChannelInboundHandlerAdapter {
    private static final String TAG = "TCPReadHandler";
    private NettyTcpClient imsClient;

    public TCPReadHandler(NettyTcpClient imsClient) {
        this.imsClient = imsClient;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Channel channel = ctx.channel();
        Log.e(TAG, "channelInactive: 频道失活，，触发重接；也可能是关闭chanel 触发了channelInactive回调");
//        if (channel != null) {
//            channel.close();
//            ctx.close();
//        }
        imsClient.onConnectInterruption();
        imsClient.resetConnect();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        Log.e(TAG, "频道出现异常，触发重连，，，");

        // 触发重连
        imsClient.onConnectInterruption();
        imsClient.resetConnect();

    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        MessageProtobuf.Msg message = (MessageProtobuf.Msg) msg;
        if (message == null || message.getHead() == null) {
            return;
        }

        int msgType = message.getHead().getMsgType();
        String msgId = message.getHead().getMsgId();
        if (TextUtils.isEmpty(msgId)) {
            Log.e(TAG, "channelRead: 消息id 为空，，，" + message.toString());
        }
        if (msgType == Constant.IM_TYPE_SEND_ACK) {
            int statusReport = message.getHead().getStatusReport();
            if (statusReport == Constant.IM_SEND_STATE_SUCCESS) {
                Log.d(TAG, "channelRead: 收到服务端发回的消息回执，消息:" + msgId + "  发送成功，statusReport：" + statusReport);
                imsClient.getMsgTimeoutTimerManager().remove(msgId);
            } else {
                Log.d(TAG, "channelRead: 收到服务端发回的消息回执，消息:" + msgId + "  发送**失败**，statusReport：" + statusReport);

            }
        } else {
            // 如果不是直播间消息，需要给服务端发一条回执
            //
            //服务端收到这个消息后，让对应的消息从 “消息重发队列”中删除
            Log.d(TAG, "channelRead: message=" + message.getBody());
            if (msgType != Constant.LIVE_ROOM_MESSAGE) {

                MessageProtobuf.Msg receivedReportMsg = MessageBuilder.buildReceivedReportMsg(msgId);
                if (receivedReportMsg != null) {
                    imsClient.sendMsg(receivedReportMsg);
                }
            }
        }
        //直播间消息不可能重复，服务端没有做重发，仅仅发一次
        if (msgType != Constant.LIVE_ROOM_MESSAGE) {
            if (MessageReceivedQueue.getInstance().isRepeatMessage(msgId)) {
                Log.w(TAG, "channelRead: 收到重复的消息， 丢弃处理 msgID:" + msgId);
                MessageReceivedQueue.getInstance().addInQueue(msgId);
                return;
            }
            MessageReceivedQueue.getInstance().addInQueue(msgId);
        }
        // 接收消息，由消息转发器转发到应用层
        imsClient.getMsgDispatcher().receivedMsg(message);
    }


}
